<template>
  <el-dialog :title="dialogtit"
             :close-on-click-modal="false"
             :visible.sync="dialogVisible"
             append-to-body
             width="400px">
    <div class="import-file">
      <el-upload ref="upload"
                 drag
                 :action="uploadUrl"
                 :headers="uploadHeaders"
                 name="file"
                 :on-success="uploadSuccess"
                 :on-error="uploadError"
                 :before-upload="beforeUpload"
                 accept=".xlsx,.xls"
                 :limit="1">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip"
             slot="tip">
          <span>只能上传.xlsx或.xls类型的文件</span>
        </div>
      </el-upload>
    </div>
    <div slot="footer"
         class="dialog-footer">
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import { fullLoadingMinxin } from '@/mixins/fullLoadingMinxin.js';
export default {
  name: 'ImportExcelFile',
  mixins: [fullLoadingMinxin],
  props: {
    dialogtit: {
      type: String,
      default: '数据导入'
    },
    uploadUrl: {
      type: String,
      default: ''
    },
    childCode: {
      type: String,
      default: 'no-child-code'
    }
  },
  data() {
    return {
      dialogVisible: false,
    }
  },
  computed: {
    uploadHeaders() {
      let headers = {
        Authorization: getToken(),
        childCode: this.childCode
      }
      return headers
    }
  },
  methods: {
    open() {
      this.dialogVisible = true;
    },
    // 上传成功回调
    uploadSuccess(res) {
      let { status, errors } = res;
      if (status == 200) {
        this.$message.success('导入文件成功');
        this.$emit('importSuccess', res);
      } else {
        let errMsg = errors[0].message
        this.msgError(`错误${status}：${errMsg}`)
        this.$emit('importError', errMsg);
      }
      this.dialogVisible = false;
      this.$refs.upload.clearFiles(); // 清除文件
      this.closeFullLoading();
    },
    // 上传失败回调
    uploadError(res) {
      console.log(res)
      this.$refs.upload.clearFiles(); // 清除文件
      this.closeFullLoading();
    },
    // 上传前验证文件格式
    beforeUpload(file) {
      console.log(file)
      const isXLSX = (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (file.type === 'application/vnd.ms-excel') || (file.type === 'application/wps-office.xlsx') || (file.type === 'application/wps-office.xls');
      if (!isXLSX) {
        this.$message.error('文件只能是【.xlsx或.xls】格式!');
      }
      if (isXLSX) {
        this.openFullLoading(); // 打开全屏loading
      }
      return isXLSX;
    },
  },
}

</script>